﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class frmIndexGenerator : Form
    {
        public frmIndexGenerator()
        {
            InitializeComponent();
        }

        private void folderPath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.lblPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {

            // Retrieving a recursive list of files of the identified path.
            string[] files = Directory.GetFiles(lblPath.Text, "*.*", SearchOption.AllDirectories);
            string strIndex = cboType.Text + ".index";

            int counter = 0;

            // Delete previous file
            File.Delete(strIndex);

            foreach (string file in files)
            {
                System.Uri uri1 = new Uri(file);
                System.Uri uri2 = new Uri(lblPath.Text + "/");
                counter++;

                Uri relativeUri = uri2.MakeRelativeUri(uri1);
                string strFile = Uri.UnescapeDataString(relativeUri.ToString());
                toolStrip.Text = "Processing Index";
                Application.DoEvents();

                // Writing relative path (string) to the index file.
                using (StreamWriter index2 = new StreamWriter(strIndex, true))
                {
                    index2.WriteLine(Uri.UnescapeDataString(relativeUri.ToString()) + "|" + GetMD5HashFromFile(file));
                }
            }

            toolStrip.Text = "Index Complete: " + counter + " files indexed.";
        }

        protected string GetMD5HashFromFile(string fileName)
        {
            // Method for generating MD5 Hash
            FileStream file = new FileStream(fileName, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

        private void frmIndexGenerator_Load(object sender, EventArgs e)
        {

        }
    }
}